import React, { useContext, useState } from 'react';
import { Input, Tooltip, message } from 'antd';
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { SerialContext } from '../context/SerialContext';
import { WriteService } from '../services/WriteService';
import { handleUpError } from '../utils/errorHandler';
import './ServoIdEditorView.css';
import { EEPromParamWrite } from '../models/up_request';

const ServoIdEditorView: React.FC = () => {
  const ctx = useContext(SerialContext);
  if (!ctx) return null;

  const { servoModel, setServoModel, globalModel, serialState } = ctx;
  const [editing, setEditing] = useState(false);
  const [inputId, setInputId] = useState(servoModel.servo_id.toString());
  const [loading, setLoading] = useState(false);

  const handleEdit = () => {
    setInputId(servoModel.servo_id.toString());
    setEditing(true);
  };

  const handleCancel = () => {
    setInputId(servoModel.servo_id.toString());
    setEditing(false);
  };

  const handleSubmit = async () => {
    if (!serialState.isSerialOpen) {
      message.error('请先打开串口');
      return;
    }
    if (!/^\d+$/.test(inputId)) {
      message.error('请输入有效的正整数ID');
      return;
    }
    const newId = Number(inputId);
    if (newId === servoModel.servo_id) {
      setEditing(false);
      return;
    }
    setLoading(true);
    try {
      await WriteService.writeEEProm(
        globalModel.global_serial_id,
        servoModel.servo_id,
        EEPromParamWrite.SetID,
        newId
      );
      setServoModel((prev) => ({ ...prev, servo_id: newId }));
      message.success(`舵机ID修改成功为 ${newId}`);
      setEditing(false);
    } catch (err) {
      handleUpError(err);
      message.error('舵机ID修改失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="servo-id-editor">
      <label className="servo-id-label">舵机 ID：</label>
      <Input
        value={inputId}
        onChange={(e) => {
          const val = e.target.value;
          if (/^\d*$/.test(val)) setInputId(val);
        }}
        disabled={!editing}
        className="servo-id-input"
        style={{ width: 100 }}
        maxLength={5}
        onPressEnter={() => {
          if (!loading) handleSubmit();
        }}
      />
      <div
        style={{ display: 'inline-flex', alignItems: 'center', marginLeft: 8 }}
      >
        <Tooltip title={editing ? (loading ? '提交中...' : '完成') : '修改'}>
          <span
            className="servo-id-icon"
            onClick={editing && !loading ? handleSubmit : handleEdit}
            style={{
              cursor: loading ? 'not-allowed' : 'pointer',
              marginRight: 8,
            }}
          >
            {editing ? <CheckOutlined spin={loading} /> : <EditOutlined />}
          </span>
        </Tooltip>
        {editing && (
          <Tooltip title="取消">
            <span
              className="servo-id-icon"
              onClick={loading ? undefined : handleCancel}
              style={{ cursor: loading ? 'not-allowed' : 'pointer' }}
            >
              <CloseOutlined />
            </span>
          </Tooltip>
        )}
      </div>
    </div>
  );
};

export default ServoIdEditorView;
